package com.sara.service.impl;

import com.sara.entity.Car;
import com.sara.entity.Customer;
import com.sara.entity.CustomerExample;
import com.sara.mapper.CarMapper;
import com.sara.mapper.CustomerMapper;
import com.sara.service.CarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Wayne
 * @date 2019/1/11
 */
@Service
public class CarServiceImpl implements CarService {

    @Autowired
    private CarMapper carMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Override
    public Car findCarByLicenceNo(String licenceNo) {


        return carMapper.selectByLicenceNo(licenceNo);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Car saveCarAndCustomer(Car car, Customer customer) {
        Integer customerId;

        CustomerExample customerExample = new CustomerExample();
        customerExample.createCriteria().andIdCardEqualTo(customer.getIdCard());
        List<Customer> customerList = customerMapper.selectByExample(customerExample);

        if(customerList == null || customerList.size() == 0){
            customerMapper.insertSelective(customer);
            customerId = customer.getId();
        }else {
            customerId = customerList.get(0).getId();
        }
        car.setCustomerId(customerId);
        carMapper.insertSelective(car);

        Car newCar = carMapper.selectByPrimaryKey(car.getId());
        Customer newCustomer = customerMapper.selectByPrimaryKey(newCar.getCustomerId());
        newCar.setCustomer(newCustomer);
        return newCar;
    }
}
